package com.applet.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.applet.exception.OrderBusinessException;
import com.applet.properties.BaiduGeoProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 百度地图Geo  地理编码    本类已在config包下，声明成bean，放入IOC
 */
//@Component
public class BaiduGeoUtil {


    //百度地理编码url
    public static final String baiduGeoLatLngUrl = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";

    //百度路线规划url
    public static final String baiduGeoDistanceUrl = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

    //配送范围限制，单位米  1km=1公里
    private static final Long  limitDistance = 5000L;

    @Resource
    private BaiduGeoProperties baiduGeoProperties;




    /**
     * 计算下单地址与店铺地址，有没有超过 5公里
     */
    public void chooseOutOfRang(String address){

        // 可重复使用的Map对象，封装参数
        Map<String, String> map = new HashMap<>();
        map.put("ak", baiduGeoProperties.getAk());
        map.put("output", "json");   //数据格式: xml/json  默认xml


        //店铺经纬度  纬度在前，经度在后
        String shopLocation = "";
        //用户下单地址经纬度
        String userLocation = "";
        // 两地距离 单位:米/m
        Long distance = null;


        // 获取商铺地址的经纬度     --- (正)地理编码
        map.put("address", baiduGeoProperties.getShopName());
        // 请求百度Geo,
        String shopCoordinateResult = HttpClientUtil.doGetHasParamsResponseJson(baiduGeoLatLngUrl, map);
        //解析
        if(StringUtils.hasLength(shopCoordinateResult)){
            JSONObject jsonObject = JSONObject.parseObject(shopCoordinateResult);
            if(jsonObject.getInteger("status") != 0){
                System.out.println("查询店铺地址 "+ baiduGeoProperties.getShopName() +" 经纬度，返回错误信息:" + jsonObject);
                throw new OrderBusinessException("店铺地址,经纬度数据解析失败");
            }
            //具体解析
            JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
            String lng = location.getString("lng");  //经度
            String lat = location.getString("lat");  //纬度
            //赋值  维度在前，经度在后
            shopLocation = lat + "," + lng;
        }
        
        // 获取用户下单地址经纬度     --- (正)地理编码
        map.put("address", address);  //覆盖了之前address
        // 请求百度Geo
        String userCoordinateResult = HttpClientUtil.doGetHasParamsResponseJson(baiduGeoLatLngUrl, map);
        // 解析
        if(StringUtils.hasLength(userCoordinateResult)){
            JSONObject jsonObject = JSONObject.parseObject(userCoordinateResult);
            if(jsonObject.getInteger("status") != 0){
                System.out.println("查询下单地址 " + address + " 经纬度，返回错误信息:" + jsonObject);
                throw new OrderBusinessException("用户下单地址，经纬度数据解析失败");
            }
            //具体解析
            JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
            String lng = location.getString("lng");  //经度
            String lat = location.getString("lat");  //纬度
            //赋值 纬度在前，经度在后
            userLocation = lat + "," + lng;
        }


        // 根据两个地址的经纬度，计算两地记录 单位: 米/m     --- 路线规划(轻量级路线规划)
        Map<String, String> distanceMap = new HashMap<>();
        distanceMap.put("ak", baiduGeoProperties.getAk());
        distanceMap.put("output", "json");            // 数据格式: xml/json 默认xml
        distanceMap.put("steps_info", "0");           // 是否下发step详情  0否 1是
        distanceMap.put("origin", shopLocation);      // 起点经纬度  纬度在前，经度在后
        distanceMap.put("destination", userLocation); // 终点经纬度

        // 请求百度Geo
        String distanceResult = HttpClientUtil.doGetHasParamsResponseJson(baiduGeoDistanceUrl, distanceMap);
        // 解析
        if(StringUtils.hasLength(distanceResult)){
            JSONObject jsonObject = JSONObject.parseObject(distanceResult);
            if(jsonObject.getInteger("status") != 0){
                System.out.println("配送路线规划，解析失败，返回错误信息:" + jsonObject);
                throw new OrderBusinessException("配送路线规划，解析失败");
            }
            //具体解析
            JSONObject object = jsonObject.getJSONObject("result");
            JSONArray jsonArray = object.getJSONArray("routes");
            JSONObject data = JSON.parseObject(JSONObject.toJSONString(jsonArray.get(0)));
            distance = data.getLong("distance");
        }

        // 判断记录是否超出5公里
        if(distance > limitDistance){
            throw new OrderBusinessException("超出配送范围");
        }
    }


}
